package org.shop.controller.app;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Address;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AddressController {
	private static Logger logger = LogManager.getLogger(AddressController.class);
	
	@Autowired
    private AddressService addressService;
	/**
	 * 获取我的所有收货地址
	 * @param req
	 * @return
	 */
	@RequestMapping("app/getAddressList")
	public String getAddressList(HttpServletRequest req){
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			List<Address> addressList = addressService.getAddressList(ud.getUserId());
			req.setAttribute("addressList", addressList);
		} catch(Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return "app/address";
	}
	
	/**
	 * 新增收货地址
	 * @param req
	 * @return
	 */
	@RequestMapping("app/addAddress")
	@ResponseBody
	public Map<String, Object> addAddress(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String userName = req.getParameter("userName");//收货人姓名
		String userPhone = req.getParameter("userPhone");//收货人手机号
		String province = req.getParameter("province");//省
		String city = req.getParameter("city");//市
		String county = req.getParameter("county");//县
		String towns = req.getParameter("towns");//镇
		String detailedAddress = req.getParameter("address");//详细地址
		try {
			addressService.updateDefaultAddress(ud.getUserId());
			Address address = new Address();
			address.setUserId(ud.getUserId());
			address.setUserName(userName);
			address.setUserPhone(userPhone);
			address.setProvince(province);
			address.setCity(city);
			address.setCounty(county);
			address.setTowns(towns);
			address.setAddress(detailedAddress);
			address.setIsDefault((byte) 1);
			addressService.insertSelective(address);
			map.put("state", 1);
			map.put("msg", "保存成功");
		} catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
			map.put("msg", "保存失败");
        }
		return map;
	}
	
	/**
	 * 修改收货地址
	 * @param req
	 * @return
	 */
	@RequestMapping("app/updateAddress")
	@ResponseBody
	public Map<String, Object> updateAddress(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String addressId = req.getParameter("addressId");
		String userName = req.getParameter("userName");//收货人姓名
		String userPhone = req.getParameter("userPhone");//收货人手机号
		String province = req.getParameter("province");//省
		String city = req.getParameter("city");//市
		String county = req.getParameter("county");//县
//		String towns = req.getParameter("towns");//镇
		String detailedAddress = req.getParameter("address");//详细地址
//		String isDefault = req.getParameter("isDefault");//是否默认地址
		try {
			Address address = new Address();
			address.setAddressId(Long.parseLong(addressId));
			address.setUserName(userName);
			address.setUserPhone(userPhone);
			address.setProvince(province);
			address.setCity(city);
			address.setCounty(county);
//			address.setTowns(towns);
			address.setAddress(detailedAddress);
//			address.setIsDefault(Byte.parseByte(isDefault));
			addressService.updateByPrimaryKeySelective(address);
			map.put("state", 1);
			map.put("msg", "修改成功");
		} catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
			map.put("msg", "修改失败");
        }
		return map;
	}
	
	/**
	 * 删除收货地址
	 * @param req
	 * @return
	 */
	@RequestMapping("app/delAddress")
	public Map<String, Object> delAddress(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String addressId = req.getParameter("addressId");
		try {
			addressService.deleteByPrimaryKey(Long.parseLong(addressId));
			map.put("state", 1);
			map.put("msg", "删除成功");
		} catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
			map.put("msg", "删除失败");
        }
		return map;
	}



	/**
	 * 设置默认收货地址
	 * @param req
	 * @return
	 */
	@RequestMapping("app/updateDefaultAddress")
	@ResponseBody
	public Map<String, Object> updateDefaultAddress(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String addressId = req.getParameter("addressId");
		try {
			Address address = new Address();
			address.setAddressId(Long.parseLong(addressId));
			address.setIsDefault((byte)1);
			address.setUserId(ud.getUserId());
			addressService.updateDefaultAddress(ud.getUserId());
			addressService.updateByPrimaryKeySelective(address);
			map.put("state", 1);
			map.put("msg", "修改成功");
		} catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
			map.put("msg", "修改失败");
        }
		return map;
	}
	
	/**
	 * 跳转到选择地址
	 * @param req
	 * @return
	 */
	@RequestMapping("app/toSelectAddress")
	public String toSelectAddress(HttpServletRequest req) {
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Integer state = Integer.parseInt(req.getParameter("state"));
		try {
			List<Address> addressList = addressService.getAddressList(ud.getUserId());
			//获取默认地址传前台
			Address personDefaultAddress = addressService.getPersonDefaultAddress(ud.getUserId());
			req.setAttribute("addressList", addressList);
			req.setAttribute("personDefaultAddress", personDefaultAddress);
			req.setAttribute("state", state);
			if(state==2) {
				String goodsIdNum = req.getParameter("goodsIdNum");
				String goodsThumsNum = req.getParameter("goodsThumsNum");
				req.setAttribute("goodsIdNum", goodsIdNum);
				req.setAttribute("goodsThumsNum", goodsThumsNum);
			}
		} catch(Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return "app/selectAddress";
	}
	
	/**
	 * 选择收货地址
	 * @param req
	 * @return
	 */
	@RequestMapping("app/selectShippingAddress")
	public String selectShippingAddress(HttpServletRequest req) {
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String addressId = req.getParameter("addressId");
		Integer state = Integer.parseInt(req.getParameter("state"));
		try {
			Address address = new Address();
			address.setAddressId(Long.parseLong(addressId));
			address.setIsDefault((byte)1);
			address.setUserId(ud.getUserId());
			addressService.updateDefaultAddress(ud.getUserId());
			addressService.updateByPrimaryKeySelective(address);
			if(state==1) {
				return "redirect:/app/userAffirmOrder";
			}else {
				Integer goodsIdNum = Integer.parseInt(req.getParameter("goodsIdNum"));
				Integer goodsThumsNum = Integer.parseInt(req.getParameter("goodsThumsNum"));
				return "redirect:/app/toNowShopping?goodsId="+goodsIdNum+"&shopcarnum="+goodsThumsNum;
			}
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		 return "";
	}
	
	
	/**
	 * 跳转修改地址
	 * @param req
	 * @return
	 */
	@RequestMapping("app/toUpdateAddress")
	public String toUpdateAddress(HttpServletRequest req) {
		Long addressId = Long.parseLong(req.getParameter("addressId"));
		try {
			Address address = addressService.selectByPrimaryKey(addressId);
			req.setAttribute("address", address);
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/updateAddress";
	}
	
	
	
}
